package com.lancer.cloud.engine.strategy;

import com.lancer.cloud.engine.annotation.CheckStrategy;
import com.lancer.cloud.engine.context.vo.RuleCheckContext;
import com.lancer.cloud.engine.util.AnnotationUtils;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 规则检查策略工程类
 * @author caijinbang
 * @date 2019-06-24 15:32
 */
@Slf4j
public class RuleCheckStrategyFactory {

    private static RuleCheckStrategyFactory factory = new RuleCheckStrategyFactory();

    /**
     * <key,类名>
     */
    private Map<String, String> cache;

    private RuleCheckStrategyFactory() {
        this.cache = AnnotationUtils.getStrategyClasses(CheckStrategy.class);
    }


    /**
     * 获取对象实例
     * @return
     */
    public static ICheckResultStrategy getStrategy(String type, RuleCheckContext context, List<RuleCheckResult> results) {
        ICheckResultStrategy strategy = null;
        String clsName = factory.getClassName(type);
        if(StringUtils.isNotBlank(clsName)) {
            try {
                Class cls = Class.forName(clsName);
                Constructor constructor = cls.getConstructor(RuleCheckContext.class, List.class);
                strategy = (ICheckResultStrategy)constructor.newInstance(context, results);
            } catch (ClassNotFoundException e) {
                log.error("******找不到类{}", clsName);
            } catch (NoSuchMethodException e) {
                log.error("******{}未提供正确的构造方法", clsName, e);
            } catch (Exception e) {
                log.error("******规则组[{}]实例构建异常", type, e);
            }
        }
        return strategy;
    }

    /**
     * 获取实现类名
     * @param type
     * @return
     */
    private String getClassName(String type) {
        //通过注解获取
        String clsName = cache.get(type);
        if(clsName != null) {
            clsName = clsName.trim();
        }
        return clsName;
    }

}
